var md5 = require('md5.js')
//获取接口地址
function getApiUrl(app,item,par) {
    var timestamp = Date.now();
    console.log('timestamp:'+timestamp)
    console.log('api_key:'+app.configData.api_key)
    
    var token = md5.hexMD5(timestamp + app.configData.api_key)
    //console.log('token:'+token)
    return app.configData.api_url + item +"?token="+token+"&timestamp="+timestamp+par;
}


/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _get(url, success, fail ) {
    var session_id = wx.getStorageSync('PHPSESSID');//本地取存储的sessionID  
    if (session_id != "" && session_id != null) {  
        var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + session_id }  
    } else {  
        var header = { 'content-type': 'application/x-www-form-urlencoded' }  
    }  
    wx.request( {
        url: url,
        header: header,
        success: function( res ) {
            success( res );
        },
        fail: function( res ) {
            fail( res );
        }
    });
}


function _post_from2(url,data, success, fail ) {
  var session_id = wx.getStorageSync('PHPSESSID');//本地取存储的sessionID  
  if (session_id != "" && session_id != null) {  
      var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + session_id }  
  } else {  
      var header = { 'content-type': 'application/x-www-form-urlencoded' }  
  } 
   wx.request( {
      url: url,
      header: header,
      method:'POST',
      data:data,
      success: function( res ) {
          success( res );
      },
      fail: function( res ) {
          fail( res );
      }
  });
}

/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_from(url,data, success, fail ) {
    var session_id = wx.getStorageSync('PHPSESSID');//本地取存储的sessionID  
    if (session_id != "" && session_id != null) {  
        var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + session_id }  
    } else {  
        var header = { 'content-type': 'application/x-www-form-urlencoded' }  
    } 
     wx.request( {
        url: url,
        header: header,
        method:'POST',
        data:data,
        success: function( res ) {
            success( res );
        },
        fail: function( res ) {
            fail( res );
        }
    });
}

 /**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_json(url,data, success, fail ) {
    wx.request( {
        url: url,
        header: {
            'content-type': 'application/json',
        },
        method:'POST',
        data:data,
        success: function( res ) {
            success( res );
        },
        fail: function( res ) {
            fail( res );
        }
    });
}

//json格式转form字符串
function json2Form(json) {  
    var str = [];  
    for(var p in json){  
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));  
    }  
    return str.join("&");  
} 

//用户提交表单提示，只有一个按钮我知道了
function showNotice(content, btnText, onBack) {
  var btnText = arguments[1] || "我知道了" //按钮文字
  var back = arguments[2] || false //是否返回上一个界面
  wx.showModal({
    content: content,
    showCancel: false,
    confirmText: btnText,
    success: function (res) {
      if (back) {
        wx.navigateBack()
      } else {
        console.log('用户点击了确定')
      }
    }
  })
}

//自动关闭的提示
function showToast(content, duration) {
  var seconds = arguments[1] || 2000 //显示时间
  wx.showToast({
    title: content,
    mask: true,
    duration: seconds
  })
}

//提交formid到后台
function add_formid(app, formid) {
  var session3rd = wx.getStorageSync('session3rd')
  console.log('get formid:' + formid)
  var post_data_formid = {
    "session3rd": session3rd,
    "form_id": formid
  }
  var url_formid = getApiUrl(app, "/Message/add_form_id", "")
  _post_from(url_formid, post_data_formid, function (res_formid) {
    console.log('提交fomrid返回')
    console.log(res_formid)
  }, function () {
    console.log('提交formid出错')
  })
}

/***
 * wxAutoImageCal 计算宽高
 * 
 * 参数 e: iamge load函数的取得的值
 * 返回计算后的图片宽高
 * {
 *  imageWidth: 100px;
 *  imageHeight: 100px;
 * }
 */
function wxAutoImageCal(e){
    console.dir(e);
    //获取图片的原始长宽
    var originalWidth = e.detail.width;
    var originalHeight = e.detail.height;
    var windowWidth = 0,windowHeight = 0;
    var autoWidth = 0,autoHeight = 0;
    var results= {};
    wx.getSystemInfo({
      success: function(res) {
        console.dir(res);
        windowWidth = res.windowWidth;
        windowHeight = res.windowHeight;
        //判断按照那种方式进行缩放
        console.log("windowWidth"+windowWidth);
        if(originalWidth > windowWidth){//在图片width大于手机屏幕width时候
          autoWidth = windowWidth;
          console.log("autoWidth"+autoWidth);
          autoHeight = (autoWidth*originalHeight)/originalWidth;
          console.log("autoHeight"+autoHeight);
          results.imageWidth = autoWidth;
          results.imageheight = autoHeight;
        }else{//否则展示原来的数据
          results.imageWidth = originalWidth;
          results.imageheight = originalHeight;
        }
      }
    })
    return results;
  }

//格式化日期
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//判断元素是否在数组内
function inArray(arr, obj) {
  if (arr == null) {
    return false;
  }
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}

//去除空数组
function emptyArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == '' || arr[i] == null || typeof (arr[i]) == undefined) {
      arr.splice(i, 1);
      i = i - 1;
    }
  }
  return arr
}

//获取字符长度
function getLength(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
      len += 2;
    } else {
      len++;
    }
  }
  return len;
}

//分解URL参数 扫描二维码分解scene参数
function get_arr_from_url(par) {
  var arr = par.split('&')
  var url_arr = new Array()
  for (var i = 0; i < arr.length; i++) {
    var arr2 = arr[i].split('=')
    url_arr[arr2[0]] = arr2[1]
  }
  return url_arr;
}

//小程序跳转
function goto_link(linktype, page_url, link, xcx_appid, xcx_path) {
  if (linktype == '' || linktype == "站内页面") {
    if (page_url == "/pages/index/index" || page_url == "/pages/category/index" || page_url == "/pages/cart/index" || page_url == "/pages/member/index") {
      wx.switchTab({
        url: page_url
      })
    } else {
      wx.navigateTo({
        url: page_url,
      })
    }
  } else if (linktype == '网址') {
    wx.navigateTo({
      url: '/pages/web/index?to_web_url=' + link,
    })
  } else if(linktype == '小程序') {
    wx.navigateToMiniProgram({
      appId: xcx_appid,
      path: xcx_path,
      success(res) {
        console.log('打开小程序成功！');
      }
    })
  }
}
    /**
   * 显示失败提示框
   */
 function showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(function() {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
 }
    /**
   * 记录formId
   * (因微信模板消息已下线，所以formId取消不再收集)
   */
  function saveFormId(formId) {
    return true;
    // let _this = this;
    // console.log('saveFormId');
    // if (formId === 'the formId is a mock one') {
    //   return false;
    // }
    // _this._post_form('wxapp.formId/save', {
    //   formId: formId
    // }, null, null, null, false);
  }

  function formatRichText(html){
    let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');

        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
        match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, "<br/>");//去掉换行符
   /*
    newContent = newContent.replace(/  /g, '<span style="margin-left: 18rpx; display:inline-block"></span>');
    newContent = newContent.replace(/&nbsp;/g, '<span style="margin-left: 18rpx; display:inline-block"></span>');
    */
    newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:0px 0;"');
    return newContent;
  }

  function formatRichText2(html){
    let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
        match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, "");//去掉换行符
    //newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:0px 0;"');
    return newContent;
  }

  function move_skip(n){
    let urls = {
      about: '/pages/guanyuwomen/guanyuwomen',
      pingtai: '/pages/pingtai-list/pingtai-list',
      service: '/pages/fuwujieshao/fuwujieshao',
      contact: '/pages/lianxi/lianxi',
    };
    // 转跳指定的页面
  
    wx.redirectTo({
      url: urls[n]
    })
  }
module.exports = {
  formatTime: formatTime,
  getApiUrl:getApiUrl,
  getLength:getLength,
  json2Form:json2Form,
  _get: _get,
  _post_from:_post_from,
  _post_json:_post_json,
  showError:showError,
  saveFormId:saveFormId,
  wxAutoImageCal:wxAutoImageCal,
  showNotice: showNotice,
  showToast: showToast,
  get_arr_from_url: get_arr_from_url,
  add_formid: add_formid,
  goto_link: goto_link,
  inArray: inArray,
  formatNumber: formatNumber,
  formatRichText: formatRichText,
  formatRichText2:formatRichText2,
  move_skip:move_skip,
}
